﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Model;
using iLangl.Customer.DAL;


namespace iLangl.Customer.Managers
{
	public class CompanyManager
	{
		#region Singelton Pattern
		private CompanyManager()
		{
		}

		private static CompanyManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the CompanyManager.
		/// </summary>
		public static CompanyManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new CompanyManager();
						}
					}
				}
				return instance;
			}
		}
		#endregion

		public void UpdateCompanyInfo(CustomerCompany company)
		{
			//Add Contacts
			if(company.Contacts != null)
			foreach (Contact contact in company.Contacts)
			{
				ContactManager.Instance.UpdateContact(contact);
			}

			DALFacade.Instance.CompanyDAL.UpdateCompany(company, null);
		}

		public bool FindCompany(CustomerCompany company)
		{
			throw new NotImplementedException();
		}

		public CustomerCompany GetCompany(String companyId)
		{
			CustomerCompany  company  =DALFacade.Instance.CompanyDAL.ReadCompany(companyId);
			FilCompany(company);
			return company;
		}

		public CustomerCompany GetCompanyBySiteId(String siteId)
		{
			CustomerCompany  company = DALFacade.Instance.CompanyDAL.ReadCompanyBySiteId(siteId);
			FilCompany(company);
			return company;
		}

		public void FilCompany(CustomerCompany company)
		{
			if (company == null)
				return;

			if((company.Contacts == null)||(company.Contacts.Length <= 0))
			{
				foreach(Contact contact in ContactManager.Instance.GetContacts(company.Id))
				{
					company.AddContact(contact);
				}
			}
		}

		public void CreateCompany(CustomerCompany company)
		{
			DALFacade.Instance.CompanyDAL.CreateCompany(company, null);
		}

		public void CreateCompany(CustomerCompany company, String primaryContactId, String userId)
		{
			Contact primarycontact = null;

			//Add Contacts
			foreach (Contact contact in company.Contacts)
			{
				if (contact.Id == primaryContactId)
				{
					primarycontact = contact;
				}

				ContactManager.Instance.CreateContact(contact);
			}


			if (primarycontact != null)
			{
				ContactManager.Instance.AssignContactToUserAccount(primarycontact, userId);
			}

			DALFacade.Instance.CompanyDAL.CreateCompany(company, null);
		}
	}
}
